package com.hue.springbootsecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author: 姚凤桥
 * @Date: 2022/5/21 10:00
 * @Description: SpringSecurity配置
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 安全拦截机制
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置表单登录的认证授
        http
            .formLogin()
            //登录成功之后跳转的地址
            .successForwardUrl("/success")
            //登录失败跳转的地址
            .failureForwardUrl("/fail")
            .and()
            .authorizeRequests()
            //访问user下的资源需要认证
            .antMatchers("/user/all").hasAnyAuthority("user-all")
            .antMatchers("/user/update").hasAnyAuthority("user-update")
            .antMatchers("/user/**").authenticated()
            //访问任何资源都不需要认证
            .anyRequest().permitAll();
    }

    /**
     * 指定密码加密方式
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
